package cn.hyy.hrm.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hyy.basic.util.AjaxResult;
import cn.hyy.hrm.client.FileClient;
import cn.hyy.hrm.util.VelocityUtils;
import feign.Response;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.Map;

@RestController
public class StaticPageController {

    @Autowired
    private FileClient fileClient;

    private Logger logger = LoggerFactory.getLogger(StaticPageController.class);

    /**
     * 模板文件暂时保持的目录
     */
    @Value("${file.template.dir}")
    private String tempPath;

    /**
     * 页面静态化【模板引擎 - velocity】
     * @param templateFileId 模板的文件id，要从fastdfs中下载
     * @param data 模板需要的数据
     * @return
     */
    @PostMapping("/staticPage")
    public AjaxResult staticPage(@RequestParam("templateFileId") String templateFileId, @RequestBody Map<String,Object> data){

        logger.debug("tempPath="+tempPath);// D:\temp

        InputStream inputStream = null;
        OutputStream outputStream = null;
        InputStream input = null;
        OutputStream os = null;
        try {
            logger.debug("templateFileId="+templateFileId);// D:\temp
            //根据模板的file下载模板的压缩包，解压
            Response response = fileClient.download(templateFileId);
            Response.Body body = response.body();
            inputStream = body.asInputStream();//文件的输入流
            //将模板文件暂时保持在某个目录下
            //判断tempPath目录是否存在，如果不存在，先创建目录
            String path = tempPath+System.currentTimeMillis()+File.separator;//防止并发问题产生  D:\temp\1586404314694
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }

            String zipPath = path+"/templates.zip"; // D:\temp\1586404314694\templates.zip

            logger.debug("zipPath="+zipPath); //  D:\temp\1586404314694\templates

            outputStream = new FileOutputStream(zipPath);
            IOUtils.copy(inputStream,outputStream);

            //解压模板文件  tempPath+"tempaltes"目录下
            ZipUtil.unzip(zipPath);


            //使用模板引擎生成一个页面 - 约定模板的页面名称叫做home.vm（约定大于配置）
           String templatePath = path+"templates/home.vm";//模板
            String targetPath = path+"home.html";//生成文件的路径
            data.put("staticRoot",path+"templates/");
            VelocityUtils.staticByTemplate(data,templatePath,targetPath);


            //将页面上传到fastdfs中，返回fileID
            //File转成MultipartFile
            File f = new File(path+"home.html");
            FileItem fileItem = new DiskFileItem("file", Files.probeContentType(f.toPath()), false, f.getName(), (int) f.length(), f.getParentFile());
            input = new FileInputStream(f);
            os = fileItem.getOutputStream();
            IOUtils.copy(input, os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            AjaxResult ajaxResult = fileClient.upload(multipartFile);
            //一系列的判断，是否成功....
            String htmlFileId = (String) ajaxResult.getResultObj();


            //页面静态化成功，则删除掉文件，防止垃圾文件一直占据存储空间
            fileClient.delete(templateFileId);
            File pathFile = new File(path);
            FileUtil.del(pathFile);//删除临时目录 TODO

            return AjaxResult.me().setSuccess(true).setMessage("成功!").setResultObj(htmlFileId);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("失败!");
        } finally {
            try {
                outputStream.close();
                input.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
